package com.ef.web.action;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.format.Colour;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

import org.apache.struts2.ServletActionContext;

import com.ef.constant.ConfirmMessage;
import com.ef.constant.ELeadsSource;
import com.ef.constant.ELeadsStatus;
import com.ef.constant.ELeadsType;
import com.ef.constant.StatusType;
import com.ef.domain.AdChannel;
import com.ef.domain.Leads;
import com.ef.domain.MarketingPlan;
import com.ef.domain.MarketingPolicy;
import com.ef.domain.School;
import com.ef.domain.User;
import com.ef.service.AdChannelService;
import com.ef.service.LeadsService;
import com.ef.service.MarketingPlanService;
import com.ef.service.MarketingPolicyService;
import com.ef.service.PTEService;
import com.ef.service.SchoolService;
import com.ef.service.UserService;

public class ImportAction extends BaseAction<Leads> {

	private static final long serialVersionUID = 1L;

	private MarketingPolicyService marketingPolicyService;
	private MarketingPlanService marketingPlanService;

	public MarketingPlanService getMarketingPlanService() {
		return marketingPlanService;
	}

	public void setMarketingPlanService(
			MarketingPlanService marketingPlanService) {
		this.marketingPlanService = marketingPlanService;
	}

	private AdChannelService adChannelService;
	private SchoolService schoolService;
	private UserService userService;
	private PTEService pTEService;

	/**
	 * 小心名字
	 * 
	 * @return
	 */
	public PTEService getpTEService() {
		return pTEService;
	}

	public void setpTEService(PTEService pTEService) {
		this.pTEService = pTEService;
	}

	private LeadsService leadsService;
	protected Map<String, String> schoolList;
	protected Map<String, String> marketingPolicyList;
	private File file;
	private String templateFilePath;
	private String tempPath; // 临时文件夹
	private String marketingPlan_hd;

	public String getMarketingPlan_hd() {
		return marketingPlan_hd;
	}

	public void setMarketingPlan_hd(String marketingPlanHd) {
		marketingPlan_hd = marketingPlanHd;
	}

	private String marketingpolicy_hd;
	private String adChannel_hd;
	private String leadsSource_hd;
	private String leadsType_hd;
	private String school_hd;

	public String doImport() {

		int sucessCount = 0;
		int failureCount = 0;

		String downloadFileName = "";

		// Map<String, String> ptes = new HashMap<String, String>();

		if (file != null) {
			MarketingPlan mpPlan = null;
			if (marketingPlan_hd != null
					&& marketingPlan_hd.trim().length() > 0) {
				mpPlan = marketingPlanService.findById(Long
						.valueOf(marketingPlan_hd));
			}
			MarketingPolicy mp = null;
			if (marketingpolicy_hd != null
					&& marketingpolicy_hd.trim().length() > 0) {
				mp = marketingPolicyService.findById(Long
						.valueOf(marketingpolicy_hd));
			}
			AdChannel adChannel = null;
			if (adChannel_hd != null && adChannel_hd.trim().length() > 0) {
				adChannel = adChannelService.findById(Long
						.valueOf(adChannel_hd));
			}
			ELeadsSource els = ELeadsSource.valueOf(leadsSource_hd);
			ELeadsType elt = ELeadsType.valueOf(leadsType_hd);
			School school = null;
			if (school_hd != null && !"".equals(school_hd)) {
				school = schoolService.findById(Long.valueOf(school_hd));
			}
			try {
				Workbook workBook = Workbook.getWorkbook(file);
				Sheet sheet = workBook.getSheet(0);

				// File templateFile = new
				// File(ServletActionContext.getServletContext().getRealPath(this.getTemplateFilePath()));
				// Workbook templateWorkbook =
				// Workbook.getWorkbook(templateFile);
				// Sheet sht = templateWorkbook.getSheet(0);

				if (sheet.getColumns() < 10) {
					this.setInfoTitle("Warning");
					this.setInfoimg("warn");
					this.setResult(ConfirmMessage.MSG_IMPORT_WARNING);
					fetchListData();
					return "import";
				}
				File f = new File(ServletActionContext.getServletContext()
						.getRealPath(this.getTempPath()));
				if (!f.exists()) {
					f.mkdirs();
				}
				downloadFileName = this.getTempPath() + "/" + getNewFileName();
				WritableWorkbook invalidWorkbook = Workbook
						.createWorkbook(new File(ServletActionContext
								.getServletContext().getRealPath(
										downloadFileName)));
				invalidWorkbook.setProtected(false);
				WritableSheet wst = invalidWorkbook.createSheet("import Leads",
						0);

				int rowCount = sheet.getRows();

				// new file title setter.
				try {
					WritableFont wf = new WritableFont(WritableFont.TIMES, 12,
							WritableFont.BOLD, false);
					WritableCellFormat wcf = new WritableCellFormat(wf);
					wcf.setBackground(Colour.GREEN);
					Cell[] titles = sheet.getRow(0);
					for (int x = 0; x < titles.length; x++) {
						wst.addCell(new Label(x + 1, 0,
								titles[x].getContents(), wcf));
					}

				} catch (RowsExceededException e1) {
					e1.printStackTrace();
				} catch (WriteException e1) {
					e1.printStackTrace();
				}

				for (int i = 1; i < rowCount; i++) {
					Cell[] cellcopy = sheet.getRow(i);
					Cell nameCell = sheet.getCell(0, i);
					Cell ageCell = sheet.getCell(1, i);
					Cell mobileCell = sheet.getCell(2, i);
					Cell phoneCell = sheet.getCell(3, i);
					Cell initVisitTimeCell = sheet.getCell(4, i);
					// 5, pte name is pass.
					Cell pnoCell = sheet.getCell(6, i);
					// 7 pte leader name is pass.
					Cell tnoCell = sheet.getCell(8, i);
					int cos = sheet.getColumns();
					Cell cityCell = null;
					if (cos > 11)
						cityCell = sheet.getCell(11, i);
					Cell commentsCell = sheet.getCell(9, i);

					Cell emailCell = null;
					if (cos > 10) {
						emailCell = sheet.getCell(10, i);
					}
					if (!mobileCell.getContents().trim().equals("")
							|| !phoneCell.getContents().trim().equals("")) {
						// 9 from name is pass.
						// Cell worknoCell = sheet.getCell(10, i);
						String lname = nameCell.getContents();
						if (lname == null || lname.trim().length() == 0) {
							lname = "unknow";
						} else {
							lname = lname.trim();
						}

						List<Leads> ls = leadsService.findByMobileOrPhone(
								mobileCell.getContents().trim(), phoneCell
										.getContents().trim());
						// List<Leads> ls2 =
						// leadsService.findByTelephone(phoneCell.getContents().trim());
						int j = 1;
						for (Cell c : cellcopy) {
							try {
								wst.addCell(new Label(j, i, c.getContents()));

							} catch (RowsExceededException e) {

								e.printStackTrace();
							} catch (WriteException e) {

								e.printStackTrace();
							}
							j++;
						}
						if (mobileCell.getContents().trim().equals("")
								&& phoneCell.getContents().trim().equals("")) {
							failureCount++;
							try {
								WritableFont wfx = new WritableFont(
										WritableFont.TIMES, 10);
								WritableCellFormat wcf1 = new WritableCellFormat(
										wfx);
								wcf1.setBackground(Colour.YELLOW);
								wst.addCell(new Label(0, i, "手机和电话必须填写其中之一",
										wcf1));
							} catch (RowsExceededException e) {
								e.printStackTrace();
							} catch (WriteException e) {
								e.printStackTrace();
							}
							continue;
						}
						if (!mobileCell.getContents().trim().equals("")
								&& mobileCell.getContents().trim().length() != 11) {
							failureCount++;
							try {
								WritableFont wfx = new WritableFont(
										WritableFont.TIMES, 10);
								WritableCellFormat wcf1 = new WritableCellFormat(
										wfx);
								wcf1.setBackground(Colour.YELLOW);
								wst.addCell(new Label(0, i, "手机号码无效", wcf1));
							} catch (RowsExceededException e) {
								e.printStackTrace();
							} catch (WriteException e) {
								e.printStackTrace();
							}
							continue;
						}
						if (!phoneCell.getContents().trim().equals("")
								&& phoneCell.getContents().trim().length() != 8
								&& phoneCell.getContents().length() != 12
								&& phoneCell.getContents().length() != 11) {
							failureCount++;
							try {
								WritableFont wfx = new WritableFont(
										WritableFont.TIMES, 10);
								WritableCellFormat wcf1 = new WritableCellFormat(
										wfx);
								wcf1.setBackground(Colour.YELLOW);
								wst.addCell(new Label(0, i, "电话号码无效", wcf1));
							} catch (RowsExceededException e) {
								e.printStackTrace();
							} catch (WriteException e) {
								e.printStackTrace();
							}
							continue;
						}
						if (pnoCell.getContents() != null
								&& pnoCell.getContents().trim().length() > 0
								&& pTEService.findByWorkNo(pnoCell
										.getContents().trim()) == null) {
							failureCount++;
							try {
								WritableFont wfx = new WritableFont(
										WritableFont.TIMES, 10);
								WritableCellFormat wcf1 = new WritableCellFormat(
										wfx);
								wcf1.setBackground(Colour.YELLOW);
								wst.addCell(new Label(0, i, "PTE工号错误", wcf1));
								failureCount++;
							} catch (RowsExceededException e) {
								e.printStackTrace();
							} catch (WriteException e) {
								e.printStackTrace();
							}
							continue;
						}
						if (tnoCell.getContents() != null
								&& tnoCell.getContents().trim().length() > 0
								&& pTEService.findByWorkNo(tnoCell
										.getContents().trim()) == null) {
							failureCount++;
							try {
								WritableFont wfx = new WritableFont(
										WritableFont.TIMES, 10);
								WritableCellFormat wcf1 = new WritableCellFormat(
										wfx);
								wcf1.setBackground(Colour.YELLOW);
								wst.addCell(new Label(0, i, "PTE Leader工号错误",
										wcf1));
							} catch (RowsExceededException e) {
								e.printStackTrace();
							} catch (WriteException e) {
								e.printStackTrace();
							}
							continue;
						}
						if (ls.size() > 0) {
							failureCount++;
							try {
								WritableFont wfx = new WritableFont(
										WritableFont.TIMES, 10);
								WritableCellFormat wcf1 = new WritableCellFormat(
										wfx);
								wcf1.setBackground(Colour.YELLOW);
								com.ef.domain.Leads temp = ls.get(0);
								User cc = temp.getCc();
								User tm = temp.getTm();
								wst.addCell(new Label(0, i, "电话号码已经存在(CC:"
										+ (cc == null ? "" : cc.getName())
										+ ",TM:"
										+ (tm == null ? "" : tm.getName())
										+ ")", wcf1));
							} catch (RowsExceededException e) {
								e.printStackTrace();
							} catch (WriteException e) {
								e.printStackTrace();
							}
							continue;
						} 
						// 判断时间
						boolean initTimeError = false;
						String iTime = initVisitTimeCell.getContents();
						Date initTimeDate = null;
						if (iTime != null && iTime.trim().length() > 0) {
							if (iTime.indexOf("/") > 0) {
								//NOTE linux 下有问题
								SimpleDateFormat format = new SimpleDateFormat(
										"MM/dd/yy");
								try {
									initTimeDate = format
											.parse(initVisitTimeCell
													.getContents());
								} catch (ParseException e) {
									initTimeError = true;
								}
							} else if (iTime.indexOf("-") > 0) {
								SimpleDateFormat format = new SimpleDateFormat(
										"MM-dd-yy");
								try {
									initTimeDate = format
											.parse(initVisitTimeCell
													.getContents());
								} catch (ParseException e) {
									initTimeError = true;
								}
							} else {
								initTimeError = true;
							}
						} else {
							initTimeError = false;
						}
						if (initTimeError) {
							// ptes.put(tnoCell.getContents().trim(),
							// tnoCell
							// .getContents().trim());
							failureCount++;
							try {
								WritableFont wfx = new WritableFont(
										WritableFont.TIMES, 10);
								WritableCellFormat wcf1 = new WritableCellFormat(
										wfx);
								wcf1.setBackground(Colour.YELLOW);
								wst
										.addCell(new Label(
												0,
												i,
												"时间格式错误[yyyy-MM-dd]或[yyyy/MM/dd]",
												wcf1));
							} catch (RowsExceededException e) {
								e.printStackTrace();
							} catch (WriteException e) {
								e.printStackTrace();
							}
							continue;
						}
						Leads leads = new Leads();
						leads.setName(lname);
						leads.setAge(ageCell.getContents());
						if (mobileCell.getContents() != null) {
							leads.setMobileTelephone(mobileCell.getContents()
									.trim());
						}
						if (phoneCell.getContents() != null) {
							leads.setTelephone(phoneCell.getContents().trim());
						}
						if (initTimeDate != null) {
							leads.setInitVisitTime(initTimeDate);
						}
						leads.setMarketingPlan(mpPlan);
						leads.setAdChannel(adChannel);
						leads.setMarketingPolicy(mp);
						leads.setLeadsSource(els);
						leads.setLeadsType(elt);
						leads.setSchool(school);
						if (pnoCell != null
								&& pnoCell.getContents().trim().length() > 0) {
							leads.setPte(pTEService.findByWorkNo(pnoCell
									.getContents()));
						}
						if (tnoCell != null
								&& tnoCell.getContents().trim().length() > 0) {
							leads.setPteLeader(pTEService.findByWorkNo(tnoCell
									.getContents()));
						}
						leads.setLastEventCommons(commentsCell.getContents()
								.trim());
						leads.setComments(commentsCell.getContents().trim());
						if (emailCell != null) {
							leads.setEmail(emailCell.getContents().trim());
						}
						leads.setLeadsStatus(ELeadsStatus.New);
						// cyg100319 如果导入人员是市场
						User user = getSessionUser();
						if (user.getTeam() != null) {
							leads.setTeam(user.getTeam());
						}
						leads.setCreateTime(new Date());
						leads.setCreateUser(getSessionUser());
						leads.setImportTime(new Date());
						leads.setImportUser(getSessionUser());
						leads.setUpdateTime(new Date());
						leads.setUpdateUser(getSessionUser());
						leads.setCity(cityCell == null ? null : cityCell
								.getContents());
						leadsService.saveOrUpdate(leads);
						sucessCount++;
						try {
							wst.addCell(new Label(0, i, "成功"));
						} catch (RowsExceededException e) {
							e.printStackTrace();
						} catch (WriteException e) {
							e.printStackTrace();
						}
					}
				}

				invalidWorkbook.write();
				try {
					invalidWorkbook.close();
				} catch (WriteException e) {

					e.printStackTrace();
				}

			} catch (BiffException e) {

				e.printStackTrace();
			} catch (IOException e) {

				e.printStackTrace();
			} finally {

			}

		}
		if (failureCount > 0) {
			this
					.setResult("Import completely,but some leads maybe import failed, check the report: click   <a href=\"../.."
							+ downloadFileName
							+ "\" target=\"_blank\" >here</a> to download");
		} else {
			this.setResult("Import sucessfully.");
		}
		this.setHomepage("/customer/Leads/list");
		fetchListData();
		return "import";
	}

	protected void fetchListData() {
		Map<String, String> map2 = new LinkedHashMap<String, String>();
		List<MarketingPolicy> mps = marketingPolicyService.findAll();
		for (MarketingPolicy m : mps) {
			map2.put(m.getId().toString(), m.getName());
		}
		marketingPolicyList = map2;
		Map<String, String> schoolMap = new LinkedHashMap<String, String>();

		List<School> schools = schoolService.findAll();

		for (School s : schools) {
			if (s.getStatus() == StatusType.VALID)
				schoolMap.put(s.getId().toString(), s.getName());
		}
		schoolList = schoolMap;

	}

	private String getNewFileName() {

		SimpleDateFormat format2 = new SimpleDateFormat("yyyyMMddHHmmss");

		String newFileName = format2.format(new Date()) + (int) Math.random()
				* 20;
		return newFileName + ".xls";
	}

	public MarketingPolicyService getMarketingPolicyService() {
		return marketingPolicyService;
	}

	public void setMarketingPolicyService(
			MarketingPolicyService marketingPolicyService) {
		this.marketingPolicyService = marketingPolicyService;
	}

	public SchoolService getSchoolService() {
		return schoolService;
	}

	public void setSchoolService(SchoolService schoolService) {
		this.schoolService = schoolService;
	}

	public LeadsService getLeadsService() {
		return leadsService;
	}

	public void setLeadsService(LeadsService leadsService) {
		this.leadsService = leadsService;
	}

	public Map<String, String> getSchoolList() {
		return schoolList;
	}

	public void setSchoolList(Map<String, String> schoolList) {
		this.schoolList = schoolList;
	}

	public Map<String, String> getMarketingPolicyList() {
		return marketingPolicyList;
	}

	public void setMarketingPolicyList(Map<String, String> marketingPolicyList) {
		this.marketingPolicyList = marketingPolicyList;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getTemplateFilePath() {
		return templateFilePath;
	}

	public void setTemplateFilePath(String templateFilePath) {
		this.templateFilePath = templateFilePath;
	}

	public String getMarketingpolicy_hd() {
		return marketingpolicy_hd;
	}

	public void setMarketingpolicy_hd(String marketingpolicyHd) {
		marketingpolicy_hd = marketingpolicyHd;
	}

	public String getAdChannel_hd() {
		return adChannel_hd;
	}

	public void setAdChannel_hd(String adChannelHd) {
		adChannel_hd = adChannelHd;
	}

	public String getLeadsSource_hd() {
		return leadsSource_hd;
	}

	public void setLeadsSource_hd(String leadsSourceHd) {
		leadsSource_hd = leadsSourceHd;
	}

	public String getLeadsType_hd() {
		return leadsType_hd;
	}

	public void setLeadsType_hd(String leadsTypeHd) {
		leadsType_hd = leadsTypeHd;
	}

	public String getSchool_hd() {
		return school_hd;
	}

	public void setSchool_hd(String schoolHd) {
		school_hd = schoolHd;
	}

	public AdChannelService getAdChannelService() {
		return adChannelService;
	}

	public void setAdChannelService(AdChannelService adChannelService) {
		this.adChannelService = adChannelService;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public String getTempPath() {
		return tempPath;
	}

	public void setTempPath(String tempPath) {
		this.tempPath = tempPath;
	}

}
